home *** CD-ROM | disk | FTP | other *** search
/ Programming an RTS Game with Direct3D / Programming an RTS Game with Direct3D.iso / Examples / Chapter 4 / Example 4.10 / app.cpp next >
Encoding:
C/C++ Source or Header  |  2006-08-01  |  7.9 KB  |  299 lines

  1. //////////////////////////////////////////////////////////////
  2. // Example 4.10: Mesh Instances                                //
  3. // Written by: C. Granberg, 2005                            //
  4. //////////////////////////////////////////////////////////////
  5.  
  6. #include <windows.h>
  7. #include <d3dx9.h>
  8. #include <vector>
  9. #include "debug.h"
  10. #include "mesh.h"
  11.  
  12. #define KEYDOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
  13. #define KEYUP(vk_code)   ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)
  14.  
  15. class APPLICATION
  16. {
  17.     public:
  18.         APPLICATION();
  19.         HRESULT Init(HINSTANCE hInstance, int width, int height, bool windowed);
  20.         HRESULT Update(float deltaTime);
  21.         HRESULT Render();
  22.         HRESULT Cleanup();
  23.         HRESULT Quit();
  24.  
  25.         void CreateMeshInstances();
  26.  
  27.     private:
  28.         IDirect3DDevice9* m_pDevice; 
  29.         MESH m_mesh1, m_mesh2;
  30.         std::vector<MESHINSTANCE> m_meshInstances;
  31.  
  32.         float m_angle;
  33.         bool m_wireframe;
  34.         D3DLIGHT9 m_light;
  35.         HWND m_mainWindow;
  36.         ID3DXFont *m_pFont;
  37. };
  38.  
  39. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd)
  40. {
  41.     APPLICATION app;
  42.  
  43.     if(FAILED(app.Init(hInstance, 800, 600, true)))
  44.         return 0;
  45.  
  46.     MSG msg;
  47.     memset(&msg, 0, sizeof(MSG));
  48.     int startTime = timeGetTime(); 
  49.  
  50.     while(msg.message != WM_QUIT)
  51.     {
  52.         if(::PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
  53.         {
  54.             ::TranslateMessage(&msg);
  55.             ::DispatchMessage(&msg);
  56.         }
  57.         else
  58.         {    
  59.             int t = timeGetTime();
  60.             float deltaTime = (t - startTime)*0.001f;
  61.  
  62.             app.Update(deltaTime);
  63.             app.Render();
  64.  
  65.             startTime = t;
  66.         }
  67.     }
  68.  
  69.     app.Cleanup();
  70.  
  71.     return msg.wParam;
  72. }
  73.  
  74. APPLICATION::APPLICATION()
  75. {
  76.     m_pDevice = NULL; 
  77.     m_mainWindow = 0;
  78.     m_angle = 0.0f;
  79.     m_wireframe = false;
  80.  
  81.     srand(GetTickCount());
  82. }
  83.  
  84. HRESULT APPLICATION::Init(HINSTANCE hInstance, int width, int height, bool windowed)
  85. {
  86.     debug.Print("Application initiated");
  87.  
  88.     //Create Window Class
  89.     WNDCLASS wc;
  90.     memset(&wc, 0, sizeof(WNDCLASS));
  91.     wc.style         = CS_HREDRAW | CS_VREDRAW;
  92.     wc.lpfnWndProc   = (WNDPROC)::DefWindowProc; 
  93.     wc.hInstance     = hInstance;
  94.     wc.lpszClassName = "D3DWND";
  95.  
  96.     //Register Class and Create new Window
  97.     RegisterClass(&wc);
  98.     m_mainWindow = CreateWindow("D3DWND", "Example 4.10: Mesh Instances", WS_EX_TOPMOST, 0, 0, width, height, 0, 0, hInstance, 0); 
  99.     SetCursor(NULL);
  100.     ShowWindow(m_mainWindow, SW_SHOW);
  101.     UpdateWindow(m_mainWindow);
  102.  
  103.     //Create IDirect3D9 Interface
  104.     IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
  105.  
  106.     if(d3d9 == NULL)
  107.     {
  108.         debug.Print("Direct3DCreate9() - FAILED");
  109.         return E_FAIL;
  110.     }
  111.  
  112.     //Check that the Device supports what we need from it
  113.     D3DCAPS9 caps;
  114.     d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps);
  115.  
  116.     //Hardware Vertex Processing or not?
  117.     int vp = 0;
  118.     if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  119.         vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
  120.     else vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  121.  
  122.     //Check vertex & pixelshader versions
  123.     if(caps.VertexShaderVersion < D3DVS_VERSION(2, 0) || caps.PixelShaderVersion < D3DPS_VERSION(2, 0))
  124.     {
  125.         debug.Print("Warning - Your graphic card does not support vertex and pixelshaders version 2.0");
  126.     }
  127.  
  128.     //Set D3DPRESENT_PARAMETERS
  129.     D3DPRESENT_PARAMETERS d3dpp;
  130.     d3dpp.BackBufferWidth            = width;
  131.     d3dpp.BackBufferHeight           = height;
  132.     d3dpp.BackBufferFormat           = D3DFMT_A8R8G8B8;
  133.     d3dpp.BackBufferCount            = 1;
  134.     d3dpp.MultiSampleType            = D3DMULTISAMPLE_NONE;
  135.     d3dpp.MultiSampleQuality         = 0;
  136.     d3dpp.SwapEffect                 = D3DSWAPEFFECT_DISCARD; 
  137.     d3dpp.hDeviceWindow              = m_mainWindow;
  138.     d3dpp.Windowed                   = windowed;
  139.     d3dpp.EnableAutoDepthStencil     = true; 
  140.     d3dpp.AutoDepthStencilFormat     = D3DFMT_D24S8;
  141.     d3dpp.Flags                      = 0;
  142.     d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
  143.     d3dpp.PresentationInterval       = D3DPRESENT_INTERVAL_IMMEDIATE;
  144.  
  145.     //Create the IDirect3DDevice9
  146.     if(FAILED(d3d9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_mainWindow,
  147.                                  vp, &d3dpp, &m_pDevice)))
  148.     {
  149.         debug.Print("Failed to create IDirect3DDevice9");
  150.         return E_FAIL;
  151.     }
  152.  
  153.     //Release IDirect3D9 interface
  154.     d3d9->Release();
  155.  
  156.     D3DXCreateFont(m_pDevice, 18, 0, 0, 1, false,  
  157.                    DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
  158.                    DEFAULT_PITCH | FF_DONTCARE, "Arial", &m_pFont);
  159.  
  160.     //Create m_light
  161.     ::ZeroMemory(&m_light, sizeof(m_light));
  162.     m_light.Type      = D3DLIGHT_DIRECTIONAL;
  163.     m_light.Ambient   = D3DXCOLOR(0.5, 0.5, 0.5, 1.0f);
  164.     m_light.Diffuse   = D3DXCOLOR(0.9, 0.9, 0.9, 1.0f);
  165.     m_light.Specular  = D3DXCOLOR(0.5, 0.5, 0.5, 1.0f);
  166.     m_light.Direction = D3DXVECTOR3(0.7f, -0.3f, 0.0f);
  167.     m_pDevice->SetLight(0, &m_light);
  168.     m_pDevice->LightEnable(0, true);
  169.  
  170.     //Sampler states
  171.     m_pDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
  172.     m_pDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
  173.     m_pDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
  174.  
  175.     //Load Meshes
  176.     if(FAILED(m_mesh1.Load("meshes/tree.x", m_pDevice)) || FAILED(m_mesh2.Load("meshes/stone.x", m_pDevice)))
  177.     {
  178.         debug.Print("Failed to load meshes");
  179.         Quit();
  180.     }
  181.  
  182.     //Create many instances of the two meshes
  183.     CreateMeshInstances();
  184.  
  185.  
  186.     return S_OK;
  187. }
  188.  
  189. HRESULT APPLICATION::Update(float deltaTime)
  190. {
  191.     //Control camera
  192.     m_angle += deltaTime * 0.5f;
  193.     D3DXMATRIX  matWorld, matView, matProj;        
  194.     D3DXVECTOR3 Eye    = D3DXVECTOR3(cos(m_angle) * 8.0f, 5.5f, sin(m_angle) * 8.0f);
  195.     D3DXVECTOR3 Lookat = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
  196.  
  197.     D3DXMatrixIdentity(&matWorld);
  198.     D3DXMatrixLookAtLH(&matView, &Eye, &Lookat, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
  199.     D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.3333f, 1.0f, 1000.0f );
  200.  
  201.     m_pDevice->SetTransform( D3DTS_WORLD,      &matWorld );
  202.     m_pDevice->SetTransform( D3DTS_VIEW,       &matView );
  203.     m_pDevice->SetTransform( D3DTS_PROJECTION, &matProj );
  204.  
  205.     if(KEYDOWN(VK_SPACE))
  206.     {
  207.         CreateMeshInstances();
  208.         Sleep(300);
  209.     }
  210.     else if(KEYDOWN('W'))
  211.     {
  212.         m_wireframe = !m_wireframe;
  213.         Sleep(300);
  214.     }
  215.     else if(KEYDOWN(VK_ESCAPE))
  216.         Quit();
  217.  
  218.     return S_OK;
  219. }    
  220.  
  221. HRESULT APPLICATION::Render()
  222. {
  223.     // Clear the viewport
  224.     m_pDevice->Clear( 0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L );
  225.  
  226.     // Begin the scene 
  227.     if(SUCCEEDED(m_pDevice->BeginScene()))
  228.     {
  229.         if(m_wireframe)m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);    
  230.         else m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
  231.  
  232.         //Render each mesh instance
  233.         for(int i=0;i<m_meshInstances.size();i++)
  234.             m_meshInstances[i].Render();
  235.  
  236.         RECT r[] = {{10, 10, 0, 0}, {10, 30, 0, 0}};
  237.         m_pFont->DrawText(NULL, "Space: Randomize Objects", -1, &r[0], DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);
  238.         m_pFont->DrawText(NULL, "W: Toggle Wireframe", -1, &r[1], DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);
  239.  
  240.         // End the scene.
  241.         m_pDevice->EndScene();
  242.         m_pDevice->Present(0, 0, 0, 0);
  243.     }
  244.  
  245.     return S_OK;
  246. }
  247.  
  248. HRESULT APPLICATION::Cleanup()
  249. {
  250.     try
  251.     {
  252.         m_mesh1.Release();
  253.         m_mesh2.Release();
  254.  
  255.         m_meshInstances.clear();
  256.  
  257.         m_pFont->Release();
  258.         m_pDevice->Release();
  259.  
  260.         debug.Print("Application terminated");
  261.     }
  262.     catch(...){}
  263.  
  264.     return S_OK;
  265. }
  266.  
  267. HRESULT APPLICATION::Quit()
  268. {
  269.     ::DestroyWindow(m_mainWindow);
  270.     ::PostQuitMessage(0);
  271.     return S_OK;
  272. }
  273.  
  274. void APPLICATION::CreateMeshInstances()
  275. {
  276.     m_meshInstances.clear();
  277.  
  278.     //Create a new instance with random type, rotation & scale
  279.     for(int y=-5;y<=5;y++)
  280.         for(int x=-5;x<=5;x++)
  281.         {
  282.             MESHINSTANCE m;
  283.             
  284.             if(rand()%2 == 0)m.SetMesh(&m_mesh1);
  285.             else m.SetMesh(&m_mesh2);
  286.  
  287.             m.SetPosition(D3DXVECTOR3(x, 0, y));
  288.  
  289.             float rX = D3DX_PI * ((rand()%50) / 1000.0f);
  290.             float rY = D3DX_PI * ((rand()%1000) / 1000.0f);
  291.             float rZ = D3DX_PI * ((rand()%50) / 1000.0f);
  292.             m.SetRotation(D3DXVECTOR3(rX, rY, rZ));
  293.  
  294.             float scale = (rand()%750 + 250) / 1000.0f;
  295.             m.SetScale(D3DXVECTOR3(scale, scale, scale));
  296.  
  297.             m_meshInstances.push_back(m);
  298.         }
  299. }